/*
 * @Author: 郑亮 z17620994877@163.com
 * @Date: 2024-04-09 09:37:14
 * @LastEditors: 郑亮 z17620994877@163.com
 * @LastEditTime: 2024-04-12 16:59:30
 * @FilePath: \node-koa2\jwt\token.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

const jwt = require('jsonwebtoken')

const verify = async (ctx, next) => {
    const url = ctx.request.url
    const token = ctx.header.token
    const API_PERMISSION_FALSE = ['/api/login', '/api/queryAutoCode', '/api/register']
    if(API_PERMISSION_FALSE.includes(url)){
        return await next()
    }

    if(!token) {
        return ctx.body = {
            code: 401,
            data: null,
            msg: '请携带token'
        }
    }

    jwt.verify(token, 'token', (err, decoded) => {
        if (err && err.message == 'jwt malformed')  {
            return ctx.body = { message: '无效 token', code: 401, data: err}
        }
        if (err && err.message === 'jwt expired') {
            return ctx.body = { message: 'token 失效', code: 404, data: err}
        }
        next()
    })
}
module.exports = {
    verify,
    jwt
}